<template>
  <div class="permissions-management">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAddRole">
        <el-icon><Plus /></el-icon>新增角色
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索角色"
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 角色列表和权限设置 -->
    <el-row :gutter="20">
      <!-- 左侧角色列表 -->
      <el-col :span="8">
        <el-card class="role-card">
          <template #header>
            <div class="card-header">
              <span>角色列表</span>
            </div>
          </template>
          <el-table
            :data="filteredRoles"
            style="width: 100%"
            highlight-current-row
            @current-change="handleRoleSelect"
          >
            <el-table-column prop="name" label="角色名称" />
            <el-table-column prop="code" label="角色编码" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleStatusChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button-group>
                  <el-button
                    type="primary"
                    link
                    @click="handleEditRole(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="danger"
                    link
                    @click="handleDeleteRole(scope.row)"
                  >
                    删除
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧权限设置 -->
      <el-col :span="16">
        <el-card class="permission-card">
          <template #header>
            <div class="card-header">
              <span>权限设置 - {{ currentRole?.name || '请选择角色' }}</span>
              <el-button
                type="primary"
                :disabled="!currentRole"
                @click="handleSavePermissions"
              >
                保存权限
              </el-button>
            </div>
          </template>
          <el-tree
            v-if="currentRole"
            ref="permissionTreeRef"
            :data="permissions"
            :props="defaultProps"
            show-checkbox
            node-key="id"
            default-expand-all
          />
          <div v-else class="empty-tip">
            请先选择一个角色
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      width="500px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="roleForm.code" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="roleForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            rows="4"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitRole">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除确认"
      width="300px"
    >
      <p>确定要删除该角色吗？相关用户的权限将被移除。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const searchQuery = ref('')
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const dialogType = ref('add')
const roleFormRef = ref(null)
const permissionTreeRef = ref(null)
const currentRole = ref(null)
const roleToDelete = ref(null)

// 角色表单数据
const roleForm = ref({
  id: '',
  name: '',
  code: '',
  status: 1,
  description: ''
})

// 表单校验规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ]
}

// 权限树配置
const defaultProps = {
  children: 'children',
  label: 'name'
}

// 模拟角色数据
const roles = ref([
  {
    id: 1,
    name: '超级管理员',
    code: 'SUPER_ADMIN',
    status: 1,
    description: '系统超级管理员'
  },
  {
    id: 2,
    name: '普通用户',
    code: 'USER',
    status: 1,
    description: '普通用户'
  }
])

// 模拟权限数据
const permissions = ref([
  {
    id: 1,
    name: '系统管理',
    children: [
      {
        id: 11,
        name: '用户管理',
        children: [
          { id: 111, name: '查看用户' },
          { id: 112, name: '新增用户' },
          { id: 113, name: '编辑用户' },
          { id: 114, name: '删除用户' }
        ]
      },
      {
        id: 12,
        name: '角色管理',
        children: [
          { id: 121, name: '查看角色' },
          { id: 122, name: '新增角色' },
          { id: 123, name: '编辑角色' },
          { id: 124, name: '删除角色' }
        ]
      }
    ]
  },
  {
    id: 2,
    name: '报表管理',
    children: [
      { id: 21, name: '查看报表' },
      { id: 22, name: '导出报表' },
      { id: 23, name: '打印报表' }
    ]
  }
])

const filteredRoles = computed(() => {
  return roles.value.filter(role =>
    Object.values(role).some(val =>
      val.toString().toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  )
})

const handleRoleSelect = (row) => {
  currentRole.value = row
  // TODO: 加载角色权限
}

const handleAddRole = () => {
  dialogType.value = 'add'
  roleForm.value = {
    id: '',
    name: '',
    code: '',
    status: 1,
    description: ''
  }
  dialogVisible.value = true
}

const handleEditRole = (row) => {
  dialogType.value = 'edit'
  roleForm.value = { ...row }
  dialogVisible.value = true
}

const handleDeleteRole = (row) => {
  roleToDelete.value = row
  deleteDialogVisible.value = true
}

const handleStatusChange = (row) => {
  ElMessage.success(`角色 ${row.name} 状态已${row.status === 1 ? '启用' : '禁用'}`)
}

const handleSubmitRole = async () => {
  if (!roleFormRef.value) return
  
  await roleFormRef.value.validate((valid) => {
    if (valid) {
      // TODO: 调用API保存角色数据
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
      dialogVisible.value = false
    }
  })
}

const handleSavePermissions = () => {
  if (!permissionTreeRef.value || !currentRole.value) return
  
  const checkedKeys = permissionTreeRef.value.getCheckedKeys()
  const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
  
  // TODO: 调用API保存角色权限
  ElMessage.success('权限保存成功')
}

const confirmDelete = () => {
  if (!roleToDelete.value) return
  
  // TODO: 调用API删除角色
  ElMessage.success('删除成功')
  deleteDialogVisible.value = false
  roleToDelete.value = null
}
</script>

<style scoped>
.permissions-management {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.search-input {
  width: 200px;
}

.role-card,
.permission-card {
  height: calc(100vh - 180px);
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.empty-tip {
  text-align: center;
  color: #909399;
  padding: 30px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 